 $currentFolder = Split-Path -parent $MyInvocation.MyCommand.Definition
 $xmlPath = join-path -path $currentFolder -childPath "Backup.xml"
 $backup = [xml](get-content $xmlPath)
 
 $server = $backup.Task.Server
 $user = $backup.Task.User
 $password = $backup.Task.Password
 
 $testConnection = sqlcmd -S $server -U $user -P $password `
								-Q "set nocount on
									select 'success'" -h -1 -W
									
 if(([String]$testConnection).Trim() -eq "success")
 {
	$currentDate = get-date -uformat "%Y-%m-%d_%H-%M-%S"
	
	foreach($backupTask in $backup.Task.Backup)
	{
		$databaseName = $backupTask.Database
		$backupFolder = $backupTask.To
		$numberOfBackups = $backupTask.NumberOfBackups
		$databaseNameRegex = "^" + $databaseName + "_"
		
		$allBackups = gci $backupFolder | ? { $_.Name -match $databaseNameRegex } 
		$backupsToKeep = $allBackups | sort-object Name -desc | select -f ($numberOfBackups -1) 
		
		foreach($backup in $allBackups)
		{
			if(($backupsToKeep -contains $backup) -eq $false) 
			{
				write-host "backup to remove $backup"
				$backupToRemove = join-path -path $backupFolder -childPath $backup
				remove-item $backupToRemove -force
			}
		}
		
		$backupName = "$databaseName" + "_" + $currentDate + ".bak"
		$backupLogicalName = "$databaseName" + "-Full Database Backup"
		$backupPath = join-path -path $backupFolder -childPath $backupName
		
		$backupSql = "BACKUP DATABASE [$databaseName] TO DISK = N'$backupPath' WITH NOFORMAT, INIT, NAME = '$backupLogicalName', SKIP, NOREWIND, NOUNLOAD, STATS = 10"
		sqlcmd -S $server -U $user -P $password -Q $backupSql -h -1 -W
	}
 }